import * as base64js from 'base64-js';

export function convertFileToBase64(file: File): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();

    reader.onloadend = () => {
      const arrayBuffer = reader.result as ArrayBuffer;
      const bytes = new Uint8Array(arrayBuffer);
      const base64String = base64js.fromByteArray(bytes);

      // 去除前缀（如果有的话）并确保填充字符正确
      const base64StringWithoutPrefix = base64String.replace(
        /^data:application\/octet-stream;base64,/,
        '',
      );
      const padding = base64StringWithoutPrefix.length % 4;
      const fixedBase64String = padding
        ? base64StringWithoutPrefix + '='.repeat(4 - padding)
        : base64StringWithoutPrefix;

      resolve(fixedBase64String);
    };

    reader.onerror = reject;
    reader.readAsArrayBuffer(file);
  });
}
